﻿using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Exception = Autodesk.AutoCAD.Runtime.Exception;

namespace AutoCadDraw
{
    public class Commands
    {
        [CommandMethod("DrawPolyline")]
        public void DrawPolyline()
        {
            string path = openFile("Polyline");
            string json = GetTxt(path);
            lclBridgeTool.Polyline polyline1= JsonConvert.DeserializeObject<lclBridgeTool.Polyline>(json);
            Polyline polyline = new Polyline();
            for (int i = 0; i < polyline1.NumberOfVertices; i++)
            {
                lclBridgeTool.Point2d point2d = polyline1.GetPoint2dAt(i);
                Point2d point2D = new Point2d(point2d.X, point2d.Y);
                double v = polyline1.GetBulgeAt(i);
                double sw = polyline1.GetStartWidthAt(i);
                double ew = polyline1.GetEndWidthAt(i);
                polyline.AddVertexAt(polyline.NumberOfVertices, point2D, v, sw,ew);
            }
            polyline.Closed = polyline1.Closed;
            AddEntity(polyline);
        }
        [CommandMethod("DrawLine")]
        public void DrawLine()
        {
            string path = openFile("Line");
            string json = GetTxt(path);
            lclBridgeTool.Line line = JsonConvert.DeserializeObject<lclBridgeTool.Line>(json);
            Point3d startPoint = new Point3d(line.StartPoint.X, line.StartPoint.Y,0);
            Point3d endPoint = new Point3d(line.EndPoint.X, line.EndPoint.Y,0);
            Line line1 = new Line(startPoint,endPoint);
            AddEntity(line1);
        }
        [CommandMethod("DrawEntitys")]
        public void DrawEntitys()
        {
            try
            {
                string path = openFile("Entitys");
                string json = GetTxt(path);
                lclBridgeTool.DBText dBText = new lclBridgeTool.DBText();//加载DrawPaperKitBridge.dll
                List<lclBridgeTool.Entity> entitys = json.ToListEntity();
                for (int i = 0; i < entitys.Count; i++)
                {
                    Entity entity = entitys[i].ToAutoCadEntity();
                    if (entity != null)
                    {
                        AddEntity(entity);
                    }
                    else
                    {//进入这里说明转换未实现

                    }
                }
            }
            catch (System.Exception e)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取txt文件内容
        /// </summary>
        /// <param name="path">文件全目录包含文件名带后缀</param>
        /// <returns></returns>
        public string GetTxt(string path)
        {
            string conStr = "";
            try
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(fs);
                conStr = reader.ReadToEnd();
            }
            catch (Exception)
            {
                conStr = "";
            }
            return conStr;
        }
        public string openFile(string title)
        {
            //打开文件

            OpenFileDialog file = new OpenFileDialog();

            file.Filter = "TXT|*.txt";

            file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            file.Multiselect = false;

            file.Title = title;

            if (file.ShowDialog() == DialogResult.Cancel)

                return null;

            var path = file.FileName;
            return path;//会返回全路径包含了文件名和后缀
        }

        public void addLine(double x, double y, double x1, double y1)
        {
            //获取当前图形数据库
            Database db = HostApplicationServices.WorkingDatabase;
            Point3d star = new Point3d(x, y, 0);
            Point3d end = new Point3d(x1, y1, 0);
            Line line = new Line(star, end);
            line.Layer = "土建文字标注";
            //定义一个指向当前数据库的事务处理，已添加直线
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(
                    db.BlockTableId, OpenMode.ForRead);

                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(
                    bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                btr.AppendEntity(line);
                trans.AddNewlyCreatedDBObject(line, true);
                trans.Commit();


            }

        }//画直线
        public void AddEntity(Entity entity) 
        {
            //获取当前图形数据库
            Database db = HostApplicationServices.WorkingDatabase;
            //定义一个指向当前数据库的事务处理，已添加直线
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(
                    db.BlockTableId, OpenMode.ForRead);

                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(
                    bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                btr.AppendEntity(entity);
                trans.AddNewlyCreatedDBObject(entity, true);
                trans.Commit();


            }
        }
    }
}
